﻿#include "scroll_mode_thread.h"
#include <QApplication>
#include <QDateTime>
#include <QDebug>

void ScrollModeADCThread::start(Priority priority) {
  thread_is_running_ = true;
  
  auto device = base_device_.toStrongRef();
  if (!device) {
    qDebug() << "ScrollModeADCThread::start() base_device is null";
    thread_is_running_ = false;
    return;
  }
  
  collect_data_length_ = device->GetCurrentDataLength();
  int sample_rate = device->GetCurrentSampleRate();

  // 采样率低于或等于100K时，采集数据长度不能低于采样率
  // 采样率高于100K时，至少读取10W数据点
  if (sample_rate <= 100000) {
    collect_data_length_ = collect_data_length_ > sample_rate ? collect_data_length_ : sample_rate;
  } else {
    collect_data_length_ = collect_data_length_ > 100000 ? collect_data_length_ : 100000;
  }

  // 调整data_大小为采集数据长度
  data_.resize(device->GetADCLegalChannelSize());
  for (int i = 0; i < data_.size(); i++) {
    data_[i].reserve(collect_data_length_);
    data_[i].resize(collect_data_length_);
  }
  
  QThread::start(priority);
}

void ScrollModeADCThread::quit() {
  qDebug() << "ScrollModeADCThread::quit() called";
  thread_is_running_ = false;
  QThread::quit();
}

void ScrollModeADCThread::run() {
  qDebug() << "ScrollModeADCThread::run() start";
  if(base_device_.isNull()){
    qDebug() << "ScrollModeADCThread::run() base_device is null";
    return;
  }

  const auto base_device = base_device_.toStrongRef();
  if (!base_device) {
    qDebug() << "ScrollModeADCThread::run() base_device toStrongRef returned null";
    return;
  }
  
  const auto channel_number = base_device->GetADCLegalChannel().size();

  int collection_count = 0;
  while (thread_is_running_) {
    // 每次循环重新获取base_device强引用并检查
    const auto current_device = base_device_.toStrongRef();
    if (!current_device) {
      qDebug() << "ScrollModeADCThread::run() device became null during execution";
      break;
    }

    // 每次循环都确保数据大小为采集长度
    for (int i = 0; i < data_.size(); i++) {
      if (data_[i].size() != collect_data_length_) {
        data_[i].resize(collect_data_length_);
      }
    }
    
    // 采集所有通道的数据
    for(int i = 0; i < channel_number; i++){
      if(!channel_state_[i]){
        continue;
      }

      if(!thread_is_running_){
        break;
      }

      auto temp_data = std::make_unique<float[]>(collect_data_length_);
      bool success = current_device->TryReadADCData(i, temp_data.get(), collect_data_length_);

      if(!thread_is_running_){
        break;
      }

      if (!success) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
        i--;
        continue;
      }

      // 将数据复制到data_缓冲区中
      for (int j = 0; j < collect_data_length_; j++) {
        data_[i][j] = temp_data[j];
      }
    }
    
    QApplication::processEvents();
    emit complete(collection_count++);
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
  }
  qDebug() << "ScrollModeADCThread::run() end";
}
